#!/usr/bin/env python3
import glob
import io
import itertools
import os
import sys
import zipfile
from os.path import isdir, join
from pathlib import Path

import requests

assert len(sys.argv) < 3

original_dir = os.getcwd()
os.chdir(os.path.dirname(os.path.realpath(__file__)))
os.chdir("..")

code_directories = [
    "electrumabc_gui",
    "electrumabc",
    "electrumabc_plugins",
]
file_types = ("*.py", "*.kv")

files = zip(
    itertools.count(start=1),
    itertools.chain.from_iterable(
        glob.iglob(f"{code_directory}/**/{file_type}", recursive=True)
        for code_directory in code_directories
        for file_type in file_types
    ),
)

with open("app.fil", "w") as f:
    for n, file in files:
        f.write(f"{Path(file)}\n")
    else:
        print("Found {} files to translate".format(n))

# Generate fresh translation template
if not os.path.exists("electrumabc/locale"):
    os.mkdir("electrumabc/locale")
cmd = (
    "xgettext -s --from-code UTF-8 --language Python --no-wrap -f app.fil"
    " --keyword=pgettext:1c,2 --keyword=npgettext:1c,2,3 -c"
    " --output=electrumabc/locale/messages.pot"
)
print("Generate template")
os.system(cmd)

os.chdir("electrumabc")

crowdin_identifier = "electron-cash"
crowdin_file_name = "files[electron-cash-client/messages.pot]"
locale_file_name = "locale/messages.pot"
crowdin_api_key = None

filename = os.path.expanduser("~/.crowdin_api_key")
if os.path.exists(filename):
    with open(filename) as f:
        crowdin_api_key = f.read().strip()

if "crowdin_api_key" in os.environ:
    crowdin_api_key = os.environ["crowdin_api_key"]

if crowdin_api_key:
    # Push to Crowdin
    print("Push to Crowdin")
    url = (
        "https://api.crowdin.com/api/project/"
        + crowdin_identifier
        + "/update-file?key="
        + crowdin_api_key
    )
    with open(locale_file_name, "rb") as f:
        files = {crowdin_file_name: f}
        response = requests.request("POST", url, files=files)
    print("", "update-file:", "-" * 20, response.text, "-" * 20, sep="\n")
    # Build translations
    print("Build translations")
    response = requests.request(
        "GET",
        "https://api.crowdin.com/api/project/"
        + crowdin_identifier
        + "/export?key="
        + crowdin_api_key,
    )
    print("", "export:", "-" * 20, response.text, "-" * 20, sep="\n")

if len(sys.argv) < 2:
    # Download & unzip
    s = requests.request(
        "GET",
        "https://crowdin.com/backend/download/project/" + crowdin_identifier + ".zip",
    ).content
    zfobj = zipfile.ZipFile(io.BytesIO(s))
else:
    zfobj = zipfile.ZipFile(
        os.path.join(os.path.relpath(original_dir, os.getcwd()), sys.argv[1])
    )

print("Unzip translations")
for name in zfobj.namelist():
    if name.endswith("/"):
        if not os.path.exists(name):
            os.mkdir(name)
    else:
        with open(name, "wb") as output:
            output.write(zfobj.read(name))

# Convert .po to .mo
print("Installing")
for lang in os.listdir("locale"):
    if not isdir(join("locale", lang)) or lang == "__pycache__":
        continue
    # Check LC_MESSAGES folder
    msg_dir = "locale/{}/LC_MESSAGES".format(lang)
    if not os.path.exists(msg_dir):
        os.mkdir(msg_dir)
    cmd = 'msgfmt --output-file="{0}/electron-cash.mo" "{0}/electron-cash.po"'.format(
        msg_dir
    )
    print("Installing", lang)
    os.system(cmd)
